﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RoboSensors.Tools
{
    public static class StringConvertHelper
    {
        public static byte[] strToHexByte(this string hexString)
        {
            hexString = hexString.Replace(" ", "");   //去除空格
            if ((hexString.Length % 2) != 0)     //判断hexstring的长度是否为偶数
            {
                hexString += "";
            }
            //声明一个长度为hexstring长度一半的字节组returnBytes
            byte[] returnBytes = new byte[hexString.Length / 2];

            for (int i = 0; i < returnBytes.Length; i++)
            {
                //将hexstring的两个字符转换成16进制的字节组
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return returnBytes;
        }
        //public static byte[] strToHexByte(string hexString)
        //{

        //}


        //字节组转换成16进制的字符串：
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");      //byte转16进制字符
                }
            }
            return returnStr;
        }
    }
}
